<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="昵称" path="name">
          <n-input v-model:value="formValue.name" placeholder="请输入昵称" />
        </n-form-item>
        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import { useMessage } from 'naive-ui';
import { updateInfo } from '@/api/authority/user'
import { useUserStore } from "@/store/modules/user";
import {cloneDeep} from "@/utils/lodashChunk";

const userStore = useUserStore()

onMounted(() => {
  let info = userStore.getUserInfo
  formValue.name = info?.nickName
})

const rules = {
  name: {
    required: true,
    message: '请输入昵称',
    trigger: 'blur',
  },
};
const formRef: any = ref(null);
const message = useMessage();

const formValue = reactive({
  name: '',
});

function formSubmit() {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      await updateInfo({
        nickName: formValue.name,
      })
      // 如果没有出现异常就会执行以下代码
      let userInfo = cloneDeep(userStore.getUserInfo)
      userInfo.nickName = formValue.name
      userStore.setUserInfo(userInfo)
      message.success('修改成功')
    } else {
      message.error('验证失败，请填写完整信息');
    }
  });
}
</script>
